package com.simple.framework.web.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.zuihou.base.R;
import com.simple.business.domain.entity.user.User;
import com.simple.business.domain.enumeration.ThirdAuthenticationEnum;
import com.simple.business.domain.vo.login.UserLoginSuccessVO;
import com.simple.business.service.user.UserService;
import com.simple.framework.security.custom.ThirdAuthenticationToken;
import com.simple.framework.web.domain.login.AuthUserThird;
import com.simple.framework.web.service.AuthUserThirdService;
import com.simple.framework.web.service.ProviderAuthenticationService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
public class ThirdLoginAuthenticationServiceImpl implements ProviderAuthenticationService {
    @Resource
    private UserService userService;
    @Resource
    private AuthUserThirdService authUserThirdService;

    @Override
    public List<ThirdAuthenticationEnum> supportsProvider() {
        return Arrays.asList(ThirdAuthenticationEnum.WEI_XIN,ThirdAuthenticationEnum.WEI_XIN_MINIPROGRAM,ThirdAuthenticationEnum.WEI_XIN_MP);
    }

    @Override
    public R<UserLoginSuccessVO> authenticate(ThirdAuthenticationToken authenticationToken, HttpServletRequest request) {
        UserLoginSuccessVO vo = new UserLoginSuccessVO();
        R<AuthUserThird> authUserByThirdCode = authUserThirdService.getAuthUserByThirdCode(authenticationToken.getThirdAuthenticationEnum(), authenticationToken.getCode());
        if (authUserByThirdCode.getIsError()) {
            return R.fail(authUserByThirdCode.getMsg());
        }
        AuthUserThird authUserInfo = authUserByThirdCode.getData();
        if (authUserInfo.getUserId() == null) {
            // 未绑定用户
            String randomAccount = authenticationToken.getThirdAuthenticationEnum().getProviderName()+RandomStringUtils.randomAlphabetic(6);
            R<UserLoginSuccessVO> register = userService.simpleRegister(randomAccount);
            if (register.getIsError()) {
                return R.fail(register.getMsg());
            }
            UserLoginSuccessVO data = register.getData();
            // 注册成功，绑定对应账号
            authUserInfo.setUserId(data.getId());
            authUserThirdService.updateById(authUserInfo);
            vo = data;
        }else {
            User user = userService.getById(authUserInfo.getUserId());
            BeanUtil.copyProperties(user, vo);
        }
        return R.success(vo);
    }
}
